//code for handing the window unload event,prevent the window close
/*
var obunload = window.onbeforeunload;

 window.onbeforeunload = function(e) {
    if(obunload)
        return obunload(e);
    event.returnValue = ux.megatron.Main.getServer().getDynamicProperty('@cdb@global@closewin');
};
window.onunload = function(e) {
    LoginUCC.logOut(function(){
        document.location.replace('/');
    });
};
 */
 //initializing the great cache
ux.cdb.admin.Cache = new ux.megatron.LRUCache({poolSize:10});

jsx3.Class.defineClass("ux.cdb.admin.AdminTheater", jsx3.gui.Block, null,
    function(theater){

        var todoClickHandler = function(event, jsxObject) {
            var name = jsxObject.getText ? jsxObject.getText() : jsxObject.toString();
            var me = this.getAncestorOfType("ux.cdb.admin.AdminTheater");
            if(me["on" + jsxObject.getName() + "Clicked"]){
                me["on" + jsxObject.getName() + "Clicked"]();
            }
        };

        theater.prototype.__onbtnHelpClicked = function(){
            var Doc = ux.megatron.Main.loadResource("/ux/cdb/admin/welcome/ui/helps.xml", "ux.cdb.admin", "Helps_HTML", "xml");
			var objDlg = new jsx3.gui.Dialog('dlgHelp',390,200,'HELP');
			objDlg.setResize(jsx3.gui.Dialog.FIXED);
			objDlg.setLeft(this.getWindow().width - 480);
			objDlg.setTop(50);
			objDlg.setText('Loading...');
			//objDlg.load('/ux/cdb/admin/welcome/ui/helps.xml');
			var root = APP.ux.megatron.getJSXByName("blkRoot_00");
			jsx3.log(root);
			root.insertBefore(objDlg);
			objDlg.loadXML(Doc);
		};
		
		theater.prototype.getWindow = function(){
			var theWidth, theHeight;
			if (window.innerWidth) {
				//alert(1);
				theWidth = window.innerWidth;
				theHeight = window.innerHeight;
			} else if (document.compatMode == 'CSS1Compat') {
				//alert(2);
				theWidth = document.documentElement.clientWidth;
				theHeight = document.documentElement.clientHeight;
			} else if (document.body) {
				//alert(3);
				theWidth = document.body.clientWidth;
				theHeight = document.body.clientHeight;
			}
			return {width: theWidth, height: theHeight};
		};

        theater.prototype.onbtnExitClicked = function(){
            ux.megatron.Dialog.confirm(ux.megatron.Main.getServer().getDynamicProperty("@cdb@Exit"), ux.megatron.Main.getServer().getDynamicProperty("@cdb@closeTip"), function(objDialog){
                ux.megatron.util.Dwr.callDwr("LoginUCC", "logOut", [], this, function(dwrObject){
                    window.onbeforeunload = function(e){};
                    window.location = "/";
                });
            }, function(objDialog){
                objDialog.doClose();
            }, ux.megatron.Main.getServer().getDynamicProperty("@cdb@Btn OK"), ux.megatron.Main.getServer().getDynamicProperty("@cdb@Btn Cancel"));
        };
        
        theater.prototype.onMenuExecute = function(objMenu, objEVENT, strRECORDID){
            /* 
			var Doc = ux.megatron.Main.loadResource("/ux/cdb/admin/docs/menu.xml", "ux.cdb.admin", "Menu_Static_Data", "xml");
			*/
			var Doc = ux.megatron.Main.getServer().getCache().getDocument("Menu_Static_Data");
			//jsx3.log(cdfDoc.instanceOf(jsx3.xml.CDF.Document) + ':' + cdfDoc.instanceOf(jsx3.xml.Document));
			var cdfDoc = jsx3.xml.CDF.Document.newDocument();
			cdfDoc.loadXML(Doc.toString()); 
            var menuRecord = cdfDoc.getRecord(strRECORDID);
            if(menuRecord && menuRecord["module"] && menuRecord["entry"]){
                this.sendLoadStageMessage(menuRecord);
            } else {
                //alert(ux.megatron.Main.getServer().getDynamicProperty("@cdb@Uncomplete"));
            }
        };

        theater.prototype.init = function(strName, vntLeft, vntTop, vntWidth, vntHeight, strHTML) {
            this.jsxsuper(strName, vntLeft, vntTop, vntWidth, vntHeight, strHTML);
        };

        theater.prototype.initialize = function() {
            ux.megatron.util.Dwr.setDwrPath('/dwr');
            ux.megatron.util.Dwr.setLiveMode(true);
            if(ux.megatron.Main.isFileSystem()) {
                ux.megatron.util.Dwr.setLiveMode(false);
            }
            ux.megatron.util.Dwr.loadDwrEngine();

            //Disable backspaceKey except key press in INPUT, TEXTAREA, TEXT
            jsx3.gui.Event.subscribe(jsx3.gui.Event.KEYDOWN, 
                function(objEvent) {
                    if (objEvent.event.backspaceKey()) { 
                        if(objEvent.event.srcElement()) {
                            var tagName = objEvent.event.srcElement().tagName.toUpperCase();
                            var srcType = objEvent.event.srcElement().type;
                            srcType = srcType ? srcType.toUpperCase() : "UNTYPE";
                            if((tagName != "INPUT" || srcType != "TEXT") && (tagName != "TEXTAREA") && (srcType != "PASSWORD")) {
                                /* @JSC :: begin DEBUG */
                                jsx3.log("objEvent backspace:" + objEvent.event.backspaceKey() + ",element:" + objEvent.event.srcElement().tagName);
                                /* @JSC :: end */
                                objEvent.event.cancelKey(); 
                            }
                        } 
                    }
                });

            ux.megatron.util.Dwr.registerCallbackHandler(function(dwrObject){
                //console.log(dwrObject);
                if(dwrObject && dwrObject.res && (dwrObject.res.flag === 0))
                    //ux.megatron.Dialog.alert("\"Flag = 0\"", dwrObject.res.msg ? dwrObject.res.msg : "No valid exception message!");
                    alert(dwrObject.res.msg ? dwrObject.res.msg : "No valid exception message!");
                else{
                }
            });
            
            try {
                ux.megatron.Main.setServer("APP.ux.megatron");
                ux.megatron.Main.setContextRootForNamespace("ux.cdb.admin", "");
            }
            catch(ex) {
                ux.megatron.Main.logException(ex);
            }
            theater.prototype.modifyPsw=function(){
                var logonName=ux.cdb.admin.Privilege.getUser().logonName;
                var pattern=/^A.*$/
                if(pattern.exec(logonName)){
					//ToDo   add some Action
					ux.megatron.Dialog.alert(ux.megatron.Main.getServer().getDynamicProperty('@cdb@ModifyPSW'), 
						ux.megatron.Main.getServer().getDynamicProperty('@cdb@global@ChangePassword'));
                }else{
	                ux.megatron.Main.loadUIResourceAsync(ux.megatron.Main.getServer().getBodyBlock(),"ux.cdb.admin", 
	                 "ux/cdb/admin/system/user/ui/UserPsw.xml", this, null);
                }
            }
            //Banner ToolBar hanlders
            this.btnExit = this.get("btnExit");
            this.btnHelp = this.get("btnHelp");
            this.btnTask = this.get("btnTask");
            this.btnFav = this.get("btnFav");
            this.btnExit.onClick = todoClickHandler;
            this.btnHelp.onClick = todoClickHandler;
            this.btnFav.onClick = this.modifyPsw;
            this.btnTask.onClick = jsx3.makeCallback(this.loadMyTask, this);
            this.get("btnClose").onClick = jsx3.makeCallback(this.closeMyTask, this);
            var container = this.getDescendantOfName("blkStageContainer_00");
            ux.cdb.admin.AdminDispatcher.setMainContainer(container);

            this.sendLoadStageMessage({
                module: "welcome",
                entry : "WelcomeStage"
            });
            var that = this;

            ux.megatron.util.Dwr.registerStatusHandler(this.loadingIconHandler, this);

            //Uncomment this line to load menu data from dwr.
            this.loadMenuData();
        };
        theater.prototype.loadingIconHandler = function(message) {
            var me = this;
            var queryType = message.objQuery.dwrType;
            if(queryType == "BeginQuery" || queryType == "EndQuery") {
                var remaining = message.dwrRemaining;
                if(parseInt(remaining,10) == 0) {
                    if(this.loadingIconHandler.timer) {
                        clearTimeout(this.loadingIconHandler.timer);
                    }
                    this.loadingIconHandler.timer = setTimeout(function() {me.get("blkLoading").hide(); }, 200);
                } else {
                    if(this.loadingIconHandler.timer) {
                        clearTimeout(this.loadingIconHandler.timer);
                    }
                    this.get("blkLoading").show()
                }
            } else {
                if (queryType == "BeginLoadInteface") {
                    this.get("blkLoading").show();
                }
            }
        };
        theater.prototype.goTask = function(taskType){
            var me = this;
            var _pollRun = function(flag, callback){
                if(flag()){
                    try{
                        callback();
                    } catch(ex){
                        console.log(ex);
                    }
                } else {
                    console.log("flag", flag);
                    setTimeout(function(){_pollRun(flag, callback);}, 100);
                }
            };
            switch(taskType){
                case 0:
                    this.onMenuExecute(null, null, 15);
                    var _a1 = function(){
                        //if(this.getDescendantsOfType("ux.cdb.admin.loan.LoanManageStage")
                    }
                    break;
                case 1:
                    this.onMenuExecute(null, null, 21);
                    break;
                case 2:
                    this.onMenuExecute(null, null, 15);
                    break;
                case 3:
                    this.onMenuExecute(null, null, 15);
                    break;
                case 4:
                    this.onMenuExecute(null, null, 25);
                    break;
                case 5:
                    this.onMenuExecute(null, null, 25);
                    break;
                case 6:
                    this.onMenuExecute(null, null, 33);
                    break;
                case 7:
                    this.onMenuExecute(null, null, 33);
                    break;
                case 8:
                    this.onMenuExecute(null, null, 33);
                    break;
                case 9:
                    this.onMenuExecute(null, null, 33);
                    break;
                case 10:
                    this.onMenuExecute(null, null, 29);
                    break;
                case 11:
                    this.onMenuExecute(null, null, 29);
                    break;
                default:
                    break;
            }
        }
        theater.prototype.loadMyTask = function(objEvent, btnTask) {
            var work = this.get("blkMyWork");
            jsx3.gui.Event.subscribeLoseFocus(this, work, "closeMyTask");
            work.setTop(objEvent.clientY() + 20);
            work.setLeft(objEvent.clientX() - work.getWidth() + 20);
            this.get("blkMyWork").show(true).repaint();
            work.get("block").getRendered().tabIndex = 1;
            ux.megatron.util.Dwr.callDwr("MyJobCountyUCC", "getAllMyWorkList", [], this, function(dwrObject){
                try{
                    var tasks = dwrObject.content.data[0];
                    var taskStr = "";
                    var _getTaskWords = function(i){
                        return ux.megatron.Main.getServer().getDynamicProperty("@cdb@myWork@Task " + i);
                    };
                    /*
                    if(tasks[0] >= 0){
                        taskStr += _getTaskWords(0)
                        + "<span style=\"margin-left:2px;margin-right:2px;color:red;font-weight:bold\">" 
                        + tasks[i] + "</span>"
                        + ux.megatron.Main.getServer().getDynamicProperty("@cdb@Unit Ming")
                        + "<br>";
                    }
                    if(tasks[1] >= 0){
                        taskStr += _getTaskWords(1)
                        + "<span style=\"margin-left:2px;margin-right:2px;color:red;font-weight:bold\">" 
                        + tasks[i] + "</span>"
                        + ux.megatron.Main.getServer().getDynamicProperty("@cdb@Unit Ming")
                        + "<br>";
                    }
                    */
                    for(var i = 0; i < 12; i ++){
                        if(tasks[i] >= 0){
                            taskStr += _getTaskWords(i) + "<span style=\"cursor:hand;margin-left:2px;margin-right:2px;color:red;font-weight:bold\" onclick=\"jsx3.html.getJSXParent(this).getAncestorOfType('ux.cdb.admin.AdminTheater').goTask(" + i + ");\">" + tasks[i] + "</span>";
                            if(i == 0){
                                taskStr += ux.megatron.Main.getServer().getDynamicProperty("@cdb@Unit Ming") + "<br>";
                            } else {
                                taskStr += ux.megatron.Main.getServer().getDynamicProperty("@cdb@Unit Fen") + "<br>";
                            }
                        }
                    }
                    if(!taskStr){
                        taskStr = ux.megatron.Main.getServer().getDynamicProperty("@cdb@myWork@No Task");
                    }
                    this.get("blkMyWork").get("tasks").setText(taskStr, true);
                } catch(ex) {
                    console.log(ex);
                }
            });
        };

        theater.prototype.closeMyTask = function() {
            this.get("blkMyWork").hide();
            jsx3.gui.Event.unsubscribeLoseFocus(this);
        };

        theater.prototype.loadMenuData = function(){
            var privil = null;
            try{
                var me = this;
                ux.cdb.admin.Privilege.loadPrivilege(
                    function(){
                        try{
                            var menuData = ux.cdb.admin.Privilege.getMenuData();
                            if(ux.megatron.Main.isFileSystem()){
                                me.getDescendantOfName("menu").setXMLUrl("/ux/cdb/admin/docs/menu.xml");
                            } else {
                                var cdfResponseDataDoc = ux.megatron.util.Dwr.toCdfDocument(menuData, "jsxroot", {"id": "jsxid", "menuChnName": "jsxtext"});
                                var cdfMenuEntryDoc = jsx3.xml.CDF.Document.newDocument();
                                cdfMenuEntryDoc.loadXML(ux.megatron.Main.loadResource("ux/cdb/admin/docs/menu.xml", "ux.cdb.admin", "Menu_Static_Data", "xml").toString());
                                //me.getDescendantOfName("menu").setXMLUrl("/ux/cdb/admin/docs/menu.xml");
								//return;
                                var walkXML = function(XMLNode){
                                    var jsxid;
                                    if(jsxid = XMLNode.getAttribute("jsxid")){
                                        var menuEntryRecord;
                                        if(menuEntryRecord = cdfMenuEntryDoc.getRecordNode(jsxid)){
                                            //XMLNode.setAttribute("jsxtext", menuEntryRecord.getAttribute("jsxtext"));
                                            var module;
                                            if(module = menuEntryRecord.getAttribute("module"))
                                                XMLNode.setAttribute("module", module);
                                            var entry;
                                            if(entry = menuEntryRecord.getAttribute("entry"))
                                                XMLNode.setAttribute("entry", entry);
                                        } else {
                                            cdfResponseDataDoc.deleteRecord(jsxid);
                                        };
                                    }
                                    var i = XMLNode.getChildIterator();
                                    while(i.hasNext()){
                                        walkXML(i.next());
                                    }
                                };
                                walkXML(cdfResponseDataDoc);
                                APP.ux.megatron.getCache().setDocument("navMenu", cdfResponseDataDoc);
                                try{
                                    var menu = me.getDescendantOfName("menu");
                                    menu.setXMLId("navMenu");
                                }catch(ex){
                                    alert(ex);
                                }
                                var userName = ux.cdb.admin.Privilege.getUser().userName;
                                var welcomeStr = ux.megatron.Main.getServer().getDynamicProperty("@cdb@welcomeStr");
                                var roleList = ux.cdb.admin.Privilege.getRoleList();
                                var roleStr = ""
                                for(var i = 0; i < roleList.length; i ++){
                                    roleStr += roleList[i]["roleName"] + "/";
                                };
                                roleStr = roleStr.substring(0, roleStr.length - 1);
                                me.getDescendantOfName("blk_Welcome").setText(welcomeStr + userName + ", " + roleStr);
                                me.getDescendantOfName("blk_Welcome").repaint();
                            }
                        } catch(ex){
                            console.log(ex);
                        }
                    }
                );
            } catch(ex){
                alert(ex.message);
            }
        };

        theater.prototype.sendLoadStageMessage = function(message) {
            var EVENT_LOADSTAGE = ux.cdb.admin.AdminDispatcher.EVENT_LOADSTAGE;
            message.subject = EVENT_LOADSTAGE;
            try {
                ux.megatron.PubSub.publish(message);    
            }
            catch (ex) {
                ux.megatron.Main.logException(ex);
            }
        };

    }
);

/*
window.onbeforeunload = function(e) {
    if(obunload)
        return obunload(e);
    ux.megatron.Dialog.confirm(ux.megatron.Main.getServer().getDynamicProperty("@cdb@Exit"), ux.megatron.Main.getServer().getDynamicProperty("@cdb@closeTip"), function(objDialog){
        ux.megatron.util.Dwr.callDwr("LoginUCC", "logOut", [], this, function(dwrObject){
            window.onbeforeunload(e);
        });
    }, function(objDialog){
        objDialog.doClose();
    }, ux.megatron.Main.getServer().getDynamicProperty("@cdb@Btn OK"), ux.megatron.Main.getServer().getDynamicProperty("@cdb@Btn Cancel"));
    return false;
}
*/
       